import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/match/detail/lq_match_detail_logic.dart';
import 'package:sports_new/entity/match/detail/lq_detail_head_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/toast_utils.dart';
import 'package:sports_new/utils/user.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/view/live/items/gift_effect_view.dart';
import 'package:sports_new/view/match_detail/basketball/lq_detail_head_widget.dart';
import 'package:sports_new/utils/date_time_utils.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import '../../../utils/constant.dart';
import '../../../utils/routes.dart';
import '../../../utils/sp_utils.dart';
import '../../../widgets/base/qkd_text.dart';
import '../../../widgets/share/share_button.dart';
import '../live/animate_live_view.dart';
import '../live/match_live_view.dart';

class LqDetailPage extends StatefulWidget {
  const LqDetailPage({super.key});

  @override
  State<LqDetailPage> createState() => _LqDetailPageState();
}

class _LqDetailPageState extends State<LqDetailPage>
    with TickerProviderStateMixin {
  late LqMatchDetailLogic logic;

  @override
  Widget build(BuildContext context) {
    return GetBuilder<LqMatchDetailLogic>(
      tag: Get.arguments.toString(),
      initState: (state) {
        logic = Get.put(LqMatchDetailLogic(), tag: Get.arguments.toString());
      },
      builder: (logic) {
        return PrimaryScrollController(
          controller: logic.scrollC,
          child: Scaffold(
            backgroundColor: logic.isPlayVideo
                ? Colours.white : Colours.main, //防止中间有一条缝
            body: ExtendedNestedScrollView(
              pinnedHeaderSliverHeightBuilder: () =>
                  MediaQuery.of(context).padding.top + kToolbarHeight + (logic.isPlayVideo?199:0),
              controller: logic.scrollC,
              physics: const NeverScrollableScrollPhysics(),
              headerSliverBuilder: (context, innerBoxIsScrolled) {
                return [
                  logic.isPlayVideo ? liveStreamHeader() : matchHeader()
                ];
              },
              body: Stack(
                children: [
                  MediaQuery.removePadding(
                    removeTop: true,
                    context: context,
                    child: Container(
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: logic.isPlayVideo
                          ? null : const BorderRadius.only(
                            topRight: Radius.circular(12),
                            topLeft: Radius.circular(12)
                        )
                      ),
                      child: LoadingWidget<bool>(
                        isLoading: logic.isLoading,
                        data: false,
                        child: () => Column(
                          children: [
                            SizedBox(
                              height: 40,
                              width: double.infinity,
                              child: Styles.tabbar(
                                controller: logic.tabController,
                                labelPadding: EdgeInsets.zero,
                                mainAxisAlignment: MainAxisAlignment.spaceAround,
                                tabs: List.generate(
                                  logic.tabs.length,
                                  (index) => Stack(
                                    alignment: AlignmentDirectional.center,
                                    children: [
                                      QkdText(logic.tabs[index],needCenter: true,),
                                      if(logic.tabsClick.contains(logic.tabs[index]) && SpUtils.getMatchClick(logic.tabs[index])?.contains("${logic.matchId}") != true)
                                      Padding(
                                        padding: const EdgeInsets.only(left: 36,bottom: 16),
                                        child: Container(
                                            height: 6,width: 6,
                                            decoration: const BoxDecoration(
                                              shape: BoxShape.circle,
                                              color: Colours.main,
                                            )
                                        ),
                                      )
                                    ],
                                  )
                                ),
                                onTap: (value) {
                                  SpUtils.setMatchClick(logic.tabs[value], "${logic.matchId}");
                                  Utils.onEvent(
                                      '${logic.liveInfo != null?"liveroom":"match_detail"}_tab',
                                      params: {'tab':logic.tabs[value]}
                                  );
                                },
                              ),
                            ),
                            Expanded(
                              child: Container(
                               color: Colours.scaffoldBg,
                                child: TabBarView(
                                  controller: logic.tabController,
                                  children: List.generate(
                                    logic.pages.length,
                                    (index) => logic.pages[index]
                                  )
                                ),
                             )
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                  const GiftEffect()
                ],
              ),
            )
          )
        );
      }
    );
  }

  liveStreamHeader() {
    return SliverAppBar(
      pinned: true,
      expandedHeight: 199,
      toolbarHeight: 199,
      leading: Container(),
      backgroundColor: Colours.black,
      systemOverlayStyle:
          const SystemUiOverlayStyle(statusBarIconBrightness: Brightness.light),
      flexibleSpace: FlexibleSpaceBar(
        collapseMode: CollapseMode.pin,
        background: SafeArea(
          child: logic.liveInfo?.vtype == 4?
          AnimateLiveView(liveInfo: logic.liveInfo,sportsId: 2):
          MatchLiveView(
            liveInfo: logic.liveInfo,
            sportsId: 2,
          ),
        ),
      )
    );
  }

  matchHeader() {
    return SliverAppBar(
      expandedHeight: 210,
      backgroundColor: Colours.transparent,
      foregroundColor: Colours.white,
      systemOverlayStyle:
        const SystemUiOverlayStyle(statusBarIconBrightness: Brightness.light),
      leading: Styles.backButton(),
      title: logic.showTitle ? _barTitle2()
        : Obx(() => Opacity(
          opacity: logic.opacity.value, child: _barTtitle1()
      )),
      titleTextStyle: const TextStyle(color: Colors.white),
      actions: [
        GestureDetector(
          onTap: () async {
            logic.isFocus = User.basketballFocuses.isFocus(logic.matchId);
            () async {
              if (!logic.isFocus) {
                Utils.onEvent("match_detail_collect", params: {'collect': 0});
                await User.basketballFocuses.focus(logic.matchId);
                logic.isFocus = User.basketballFocuses.isFocus(logic.matchId);
                ToastUtils.showDismiss("关注${logic.isFocus ? "成功" : "失败"}");
              } else {
                Utils.onEvent("match_detail_collect", params: {'collect': 1});
                await User.basketballFocuses.unFocus(logic.matchId);
                logic.isFocus = User.basketballFocuses.isFocus(logic.matchId);
                ToastUtils.showDismiss("取消关注${logic.isFocus ? "失败" : "成功"}");
              }
            }.call();
          },
          child: Image.asset(
            Utils.getImgPath(
              logic.isFocus ? "match_focus.png" : "match_unfocus.png"
            ),
            color: Colours.white,
            width: 24,
          )
        ),
        Container(width: 8),
        ShareButton(
          route: '/tg/matches/lanqiu/fenxi/${logic.matchId}',
          title:
          "${logic.detail?.awayTeamName} vs ${logic.detail?.homeTeamName}",
          content: "${logic.detail?.matchTime}",
          onTap: () => Utils.onEvent("match_detail_share"),
        ),
        Container(width: 16)
      ],
      flexibleSpace: FlexibleSpaceBar(
        collapseMode: CollapseMode.pin,
        background: Obx(() => Opacity(
          opacity: logic.opacity.value,
          child: LqDetailHeadWidget(
            detail: logic.detail,
            id: logic.matchId,
            logic: logic
          ),
        )),
      ),
    );
  }

  Widget _barTtitle1() {
    final kind = {
      1: '常规赛',
      2: '季后赛',
      3: '季前赛',
      4: '全明星',
      5: '杯赛',
      6: '附加赛'
    }[logic.detail?.kind ?? 0];
    return Column(
      children: [
        DefaultTextStyle(
          style:
              const TextStyle(color: Colors.white, fontSize: 14, height: 1.2),
          child: GestureDetector(
            onTap: () => Get.toNamed(Routes.leagueDetail,
                parameters: {"type": "1"}, arguments: logic.detail?.leagueId),
            child: Column(
              children: [
                if ((logic.detail?.statusId ?? -1) >= 10)
                  QkdText(logic.detail?.matchDateTime?.formatedString('MM-dd HH:mm') ?? ""),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    QkdText(logic.detail?.leagueName ?? ""),
                    if (kind != null)
                      QkdText(
                        kind,
                      ).marginOnly(left: 6)
                  ],
                ),
              ],
            ),
          ),
        )
      ],
    );
  }

  Widget _barTitle2() {
    final statusid = logic.detail?.statusId ?? 0;
    // log("detail status id = ${statusid}");
    Widget mid = Container();
    if (statusid == 1) {
      mid = QkdText("${logic.detail?.matchDateTime?.formatedString('MM-dd\nHH:mm')}",maxLines: 2);
    } else if (statusid == 10) {
      mid = QkdText("${logic.detail?.awayScore}-${logic.detail?.homeScore}");
    } else if ((statusid < 1) || (statusid > 8)) {
      mid = QkdText(logic.detail?.statusMap[statusid] ?? "");
    } else {
      mid = Column(
        children: [
          QkdText(logic.detail?.statusMap[statusid] ?? ""),
          QkdText("${logic.detail?.awayScore}-${logic.detail?.homeScore}")
        ],
      );
    }

    return DefaultTextStyle(
        style: const TextStyle(color: Colors.white),
        textAlign: TextAlign.center,
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        child: Row(
          children: [
            Expanded(child: QkdText(logic.detail?.awayTeamName ?? "")),
            const SizedBox(width: 5),
            mid,
            const SizedBox(width: 5),
            Expanded(child: QkdText("${logic.detail?.homeTeamName}[主]")),
          ],
        ));
  }
}
